package cn.xuchunh.campusbbs.ui.fragments;

import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.android.volley.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.adapter.TopicListAdapter;
import cn.xuchunh.campusbbs.base.BaseRecyclerViewAdapter;
import cn.xuchunh.campusbbs.base.BaseRefreshListFragment;
import cn.xuchunh.campusbbs.bean.Topic;
import cn.xuchunh.campusbbs.net.HttpRequestManager;
import cn.xuchunh.campusbbs.net.XJsonListener;
import cn.xuchunh.campusbbs.ui.activities.TopicDetailActivity;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;
import cn.xuchunh.campusbbs.utils.JsonKey;
import cn.xuchunh.campusbbs.viewholder.TopicViewHolder;

/**
 * Created by XuChunH on 2015/9/22.
 */
public class SearchFragment extends BaseRefreshListFragment<TopicViewHolder, Topic> {

    private String query = "";
    private int searchId = 0;

    public static SearchFragment getInstance(String query) {
        SearchFragment searchFragment = new SearchFragment();
        Bundle args = new Bundle();
        args.putString(IntentParamsKey.SEARCH_QUERY, query);
        searchFragment.setArguments(args);
        return searchFragment;
    }

    public SearchFragment() {
    }

    @Override
    protected RecyclerView.LayoutManager createLayoutManager() {
        return new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
    }

    @Override
    protected BaseRecyclerViewAdapter<TopicViewHolder, Topic> createAdapter() {
        return new TopicListAdapter(getActivity());
    }

    @Override
    protected List<Topic> parse(JSONObject jsonObject) throws JSONException {
        List<Topic> list = new ArrayList<>();
        JSONArray jsonArray = jsonObject.optJSONArray(JsonKey.LIST);
        int size = jsonArray.length();
        JSONObject topicJson;
        for (int i = 0; i < size; i++) {
            topicJson = jsonArray.optJSONObject(i);
            Topic topic = new Topic();
            topic.setForumId(topicJson.optInt(JsonKey.BOARD_ID));
            topic.setId(topicJson.optInt(JsonKey.TOPIC_ID));
            topic.setTitle(topicJson.optString(JsonKey.TITLE));
            topic.setUserId(topicJson.optInt(JsonKey.USER_ID));
            topic.setUserNickName(topicJson.optString(JsonKey.USER_NICK_NAME));
            String lastReplyDate = topicJson.optString(JsonKey.LAST_REPLY_DATE);
            topic.setLastReplyDate(TextUtils.isEmpty(lastReplyDate) ? 0 : Long.valueOf(lastReplyDate));
            topic.setVote(topicJson.optInt(JsonKey.VOTE));
            topic.setHot(topicJson.optInt(JsonKey.HOT) != 0);
            topic.setHits(topicJson.optInt(JsonKey.HITS));
            topic.setReplies(topicJson.optInt(JsonKey.REPLIES));
            topic.setEssence(topicJson.optInt(JsonKey.ESSENCE) != 0);
            topic.setTop(topicJson.optInt(JsonKey.TOP) != 0);
            topic.setStatus(topicJson.optInt(JsonKey.STATUS));
            topic.setSubject(topicJson.optString(JsonKey.SUBJECT));
            topic.setPicPath(topicJson.optString(JsonKey.PIC_PATH));
            topic.setSortId(topicJson.optInt(JsonKey.SORT_ID));
            topic.setTypeId(topicJson.optInt(JsonKey.TYPE_ID));
            list.add(topic);
        }
        int hasNext = jsonObject.optInt(JsonKey.HAS_NEXT);
        getAdapter().setHasMore(hasNext != 0);
        searchId = jsonObject.optInt(JsonKey.SEARCHID);
        return list;
    }

    @Override
    protected void loadDataFromServer() {
        HttpRequestManager.getInstance(AppContext.getInstance())
                .search(
                        20,
                        getPage(),
                        query,
                        searchId,
                        jsonListener,
                        new SimpleErrorListener(),
                        getVolleyTag()
                );
    }

    @Override
    protected void loadDataFromCache() {

    }

    @Override
    public String getVolleyTag() {
        return SearchFragment.class.getSimpleName();
    }

    @Override
    public String getCacheKey() {
        return null;
    }

    @Override
    protected void beforeInitView() {
        super.beforeInitView();
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_search, menu);
        final MenuItem menuItem = menu.findItem(R.id.menu_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint(getString(R.string.search_hint));
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                query = s;
                setTitle(query);
                setPage(1);
                loadDataFromServer();
                menuItem.collapseActionView();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    @Override
    public void handleArgs(Bundle args) {
        if (args != null) {
            query = args.getString(IntentParamsKey.SEARCH_QUERY, "");
            setTitle(query);
        }
    }

    @Override
    public void onItemClick(int position, View item) {
        TopicDetailActivity.launch(getActivity(), getAdapter().getItem(position));
    }

    private XJsonListener<List<Topic>> jsonListener = new XJsonListener<List<Topic>>() {
        @Override
        public List<Topic> parseJson(String json) throws Exception {
            try {
                JSONObject jsonObject = new JSONObject(json).optJSONObject(JsonKey.PHPRESULT);
                if (jsonObject.optInt(JsonKey.RS) == 1) {
                    return parse(jsonObject);
                } else {
                    throw new Exception(jsonObject.optJSONObject(JsonKey.HEAD).optString(JsonKey.ERR_INFO));
                }
            } catch (JSONException ignored) {
                throw new Exception(getString(R.string.error_parse_json));
            }

        }

        @Override
        public void onResponse(List<Topic> response) {
            loadDataFinished(true, response);
        }
    };


}
